package com.hp.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.time.LocalTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author hp
 */
@RestController
@RequestMapping("/sse")
public class SseController {

    // 创建线程池处理异步事件（根据需求调整线程数）
    private final ExecutorService executor = Executors.newCachedThreadPool();

    /**
     * SSE 服务端推送接口
     *
     * @param clientId 客户端标识（用于多客户端区分）
     */
    @GetMapping(path = "/sse-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamEvents(@RequestParam String clientId) {
        // 设置1小时超时（可根据需求调整）
        SseEmitter emitter = new SseEmitter(3600_000L);

        // 启动独立线程模拟实时数据推送
        executor.execute(() -> {
            try {
                // 模拟持续发送事件
                for (int i = 0; i < 10; i++) {
                    // 构造SSE格式数据
                    String eventData = String.format("Client %s - Time: %s - Count: %d", clientId, LocalTime.now(), i);

                    // 发送事件（可自定义事件类型）
                    emitter.send(
                            SseEmitter.event()
                                    // 事件ID（客户端可追踪）
                                    .id(String.valueOf(i))
                                    // 事件名称
                                    .name("server-time-event")
                                    // 事件内容
                                    .data(eventData)
                    );

                    // 间隔1秒
                    Thread.sleep(1000);
                }

                // 正常结束
                emitter.complete();
            } catch (InterruptedException | IOException e) {
                // 处理客户端断开连接
                emitter.completeWithError(e);
            }
        });

        // 设置连接关闭时的回调
        emitter.onCompletion(() -> System.out.println("SSE connection completed: " + clientId));
        emitter.onTimeout(() -> System.out.println("SSE connection timeout: " + clientId));
        emitter.onError((ex) -> System.out.println("SSE error: " + ex.getMessage()));

        return emitter;
    }
}
